
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { BaseService } from '@/common/base/service';

import { MenuEntity } from './entities/menu.entity';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';

@Injectable()
export class MenuService extends BaseService<MenuEntity> {
  constructor(
    @InjectRepository(MenuEntity) private repo: Repository<MenuEntity>,
  ) {
    super(repo);
  }

  // 获取树形结构的菜单
  async findAllTree(type): Promise<MenuEntity[]> {
    const all = await this.repo.find();
    return this.listToTree(all, 0, type);
  }

  // 将平铺的菜单转为树结构
  private listToTree(list: MenuEntity[], parentId, type): any[] {
    if (type === 'route') {
      return list
        .filter(item => item.parentId === parentId && item.type !== 3)
        .map(item => {
          return {
            ...item,
            children: this.listToTree(list, item.id, type)
          }
        })
    }
    if (type === 'menu') {
      return list
        .filter(item => item.parentId === parentId)
        .map(item => ({
          ...item,
          children: this.listToTree(list, item.id, type)
        }))
    }
  }
 
  //创建菜单
  async create(dto: CreateMenuDto) {
    console.log('4444',dto)
    return this.repo.save(dto);
  }

  //修改菜单
  async update(id: number, dto: UpdateMenuDto) {
    console.log('333',dto)
    const menu = await this.repo.findOne({ where: { id } })
    Object.assign(menu, dto) //合并更新字段
    return this.repo.save(menu); // 保存到数据库
  }

  //删除指定数据
  async remove(id: number) {
    const result = await this.repo.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException(`未找到id为 ${id} 的菜单`);
    }
    return { message: '菜单已删除' };
  }


}
